<template>
  <div class="chart-page h-screen flex flex-col">
    <!-- 图表区域 -->
    <div class="flex-shrink-0" style="height: 35vh">
      <ARow :gutter="[8, 8]" class="h-full">
        <ACol :span="24" :md="12" class="h-full">
          <ACard title="财务数据柱状图" class="chart-card h-full" headStyle="padding: 6px 12px; min-height: 32px;" bodyStyle="padding: 10px;">
            <div ref="barDomRef" class="chart-container h-full overflow-hidden"></div>
          </ACard>
        </ACol>
        <ACol :span="24" :md="12" class="h-full">
          <ACard title="财务数据饼图" class="chart-card h-full" headStyle="padding: 6px 12px; min-height: 32px;" bodyStyle="padding: 10px;">
            <div ref="pieDomRef" class="chart-container h-full overflow-hidden"></div>
          </ACard>
        </ACol>
      </ARow>
    </div>

    <!-- 表格区域 -->
    <div class="flex-grow overflow-hidden mt-6px">
      <ACard class="h-full flex flex-col" headStyle="padding: 6px 12px; min-height: 32px;" bodyStyle="padding: 10px;">
        <div class="chart-title-wrapper" style="display: flex; justify-content: space-between; align-items: center;">
          <div class="text-14px font-bold chart-title-text">财务数据表格</div>
          <div style="margin-top: -10px;">
            <AButton type="primary" @click="exportToExcel" class="mr-2">导出Excel</AButton>
            <AButton @click="importFromExcel" class="mr-2">导入Excel</AButton>
          </div>
        </div>
        <div class="flex-grow overflow-hidden flex flex-col">
          <div class="custom-table-wrapper flex-grow flex flex-col">
            <div class="table-container">
              <div class="table-header sticky top-0 z-10">
                <div class="table-row table-head">
                  <div
                    class="table-cell sortable"
                    v-for="col in tableColumns"
                    :key="col.key"
                    :style="{ width: col.width + '%' }"
                    @click="handleSort(col.key)"
                  >
                    {{ col.title }}
                    <span class="ml-1">
                      <span
                        class="cursor-pointer hover:text-gray-300"
                        :style="{ color: sortState.field === col.key && sortState.order === 'asc' ? '#fff' : '' }"
                      >↑</span>
                      <span
                        class="cursor-pointer hover:text-gray-300"
                        :style="{ color: sortState.field === col.key && sortState.order === 'desc' ? '#fff' : '' }"
                      >↓</span>
                    </span>
                  </div>
                </div>
              </div>
              <div class="table-body overflow-auto flex-grow">
                <div
                  class="table-row"
                  v-for="(row, index) in sortedTableData"
                  :key="row.key"
                  :class="getRowClass(index)"
                >
                  <div class="table-cell" v-for="col in tableColumns" :key="col.key" :style="{ width: col.width + '%' }">
                    <div class="cell-content">{{ row[col.dataIndex] }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="table-pagination">
            <div class="flex items-center">
              <input
                ref="fileInput"
                type="file"
                accept=".xlsx,.xls"
                @change="handleFileUpload"
                style="display: none;"
              />
            </div>
            <APagination
              v-model:current="pagination.current"
              v-model:page-size="pagination.pageSize"
              :total="pagination.total"
              :show-size-changer="pagination.showSizeChanger"
              :page-size-options="pagination.pageSizeOptions"
              :show-quick-jumper="pagination.showQuickJumper"
              :show-total="pagination.showTotal"
              @change="handlePageChange"
            />
          </div>
        </div>
      </ACard>
    </div>
  </div>
</template>

<script setup lang="jsx">
import { ref, reactive, computed, onMounted, nextTick } from 'vue';
import { useEcharts } from '@/hooks/common/echarts';
import * as XLSX from 'xlsx';
import { message } from 'ant-design-vue';

// 柱状图
const { domRef: barDomRef, updateOptions: updateBarOptions } = useEcharts(
  () => ({
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['收入', '支出', '利润'],
      top: 0,
      right: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '收入',
        type: 'bar',
        barGap: 0,
        data: [120000, 132000, 101000, 134000, 90000, 230000, 210000, 120000, 132000, 101000, 134000, 190000],
        label: {
          show: true,
          position: 'top',
          fontSize: 9
        }
      },
      {
        name: '支出',
        type: 'bar',
        data: [50000, 62000, 41000, 54000, 40000, 110000, 90000, 50000, 62000, 41000, 54000, 80000],
        label: {
          show: true,
          position: 'inside',
          fontSize: 9
        }
      },
      {
        name: '利润',
        type: 'bar',
        data: [70000, 70000, 60000, 80000, 50000, 120000, 120000, 70000, 70000, 60000, 80000, 110000],
        label: {
          show: true,
          position: 'bottom',
          fontSize: 9,
          offset: [0, -10]
        }
      }
    ]
  }),
  false
);

// 饼图
const { domRef: pieDomRef, updateOptions: updatePieOptions } = useEcharts(
  () => ({
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: '',
      left: 'right',
      top: 0,
      right: 10
    },
    series: [
      {
        name: '财务占比',
        type: 'pie',
        radius: '50%',
        data: [
          { value: 1200000, name: '销售收入' },
          { value: 500000, name: '材料成本' },
          { value: 300000, name: '人工成本' },
          { value: 200000, name: '制造费用' },
          { value: 200000, name: '其他费用' }
        ],
        label: {
          show: true,
          formatter: '{b}: {d}%',
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }),
  false
);

// 表格数据
const tableColumns = [
  {
    title: '月份',
    dataIndex: 'month',
    key: 'month',
    fixed: 'left',
    width: 11
  },
  {
    title: '销售收入',
    dataIndex: 'salesRevenue',
    key: 'salesRevenue',
    width: 11
  },
  {
    title: '材料成本',
    dataIndex: 'materialCost',
    key: 'materialCost',
    width: 11
  },
  {
    title: '人工成本',
    dataIndex: 'laborCost',
    key: 'laborCost',
    width: 11
  },
  {
    title: '制造费用',
    dataIndex: 'manufacturingCost',
    key: 'manufacturingCost',
    width: 11
  },
  {
    title: '其他费用',
    dataIndex: 'otherCost',
    key: 'otherCost',
    width: 11
  },
  {
    title: '总收入',
    dataIndex: 'totalIncome',
    key: 'totalIncome',
    width: 11
  },
  {
    title: '总支出',
    dataIndex: 'totalExpenses',
    key: 'totalExpenses',
    width: 11
  },
  {
    title: '净利润',
    dataIndex: 'netProfit',
    key: 'netProfit',
    fixed: 'right',
    width: 12
  }
];

// 存储所有数据（包括原始数据和导入的数据）
const allTableData = ref([]);

// 生成大量财务数据用于分页展示
const generateFinancialData = (page, pageSize) => {
  const data = [];
  const totalItems = 1000; // 总共1000条数据

  // 根据页码和页面大小生成对应的数据
  const startIndex = (page - 1) * pageSize;
  const endIndex = Math.min(startIndex + pageSize, totalItems);

  for (let i = startIndex; i < endIndex; i++) {
    const year = 2020 + Math.floor(i / 12);
    const month = (i % 12) + 1;
    const monthLabel = `${year}年${month}月`;

    // 生成随机财务数据
    const salesRevenue = Math.floor(Math.random() * 300000) + 80000;
    const materialCost = Math.floor(Math.random() * 100000) + 30000;
    const laborCost = Math.floor(Math.random() * 60000) + 20000;
    const manufacturingCost = Math.floor(Math.random() * 50000) + 10000;
    const otherCost = Math.floor(Math.random() * 40000) + 5000;
    const totalIncome = salesRevenue;
    const totalExpenses = materialCost + laborCost + manufacturingCost + otherCost;
    const netProfit = totalIncome - totalExpenses;

    data.push({
      key: i,
      month: monthLabel,
      salesRevenue: salesRevenue.toLocaleString(),
      materialCost: materialCost.toLocaleString(),
      laborCost: laborCost.toLocaleString(),
      manufacturingCost: manufacturingCost.toLocaleString(),
      otherCost: otherCost.toLocaleString(),
      totalIncome: totalIncome.toLocaleString(),
      totalExpenses: totalExpenses.toLocaleString(),
      netProfit: netProfit.toLocaleString()
    });
  }

  return data;
};

// 更新当前页数据
const updateCurrentPageData = () => {
  const startIndex = (pagination.current - 1) * pagination.pageSize;
  const endIndex = startIndex + pagination.pageSize;
  tableData.value = allTableData.value.slice(startIndex, endIndex);
};

// 获取行类名
const getRowClass = (index) => {
  return index % 2 === 0 ? 'table-row-even' : 'table-row-odd';
};

// 排序状态
const sortState = reactive({
  field: '',
  order: ''
});

// 处理排序
const handleSort = (field) => {
  console.log('Sorting by field:', field);
  console.log('Current sort state:', sortState);
  // 如果点击的是当前排序字段，则切换排序方式
  if (sortState.field === field) {
    if (sortState.order === 'asc') {
      sortState.order = 'desc';
    } else if (sortState.order === 'desc') {
      sortState.order = '';
      sortState.field = '';
    } else {
      sortState.order = 'asc';
    }
  } else {
    // 点击新字段，默认升序
    sortState.field = field;
    sortState.order = 'asc';
  }
};

// 分页相关状态
const pagination = reactive({
  current: 1,
  pageSize: 50,
  total: 1000,
  showSizeChanger: true,
  pageSizeOptions: ['50', '100', '200', '500'],
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条数据`
});

// 表格数据
const tableData = ref([]);

// 初始化数据
onMounted(async () => {
  // 生成初始的1000条数据
  allTableData.value = [];
  for (let i = 0; i < 20; i++) { // 20页 * 50条 = 1000条
    const pageData = generateFinancialData(i + 1, 50);
    allTableData.value.push(...pageData);
  }
  updateCurrentPageData();

  await nextTick();
  updateBarOptions();
  updatePieOptions();
});

// 处理分页变化
const handlePageChange = (current, pageSize) => {
  pagination.current = current;
  pagination.pageSize = pageSize;
  updateCurrentPageData();
  // 重置排序状态
  sortState.field = '';
  sortState.order = '';
};

// 计算排序后的数据
const sortedTableData = computed(() => {
  if (!sortState.field || !sortState.order) {
    return tableData.value;
  }

  // 创建数据副本以避免修改原始数据
  const sortedData = [...tableData.value];

  return sortedData.sort((a, b) => {
    let aValue = a[sortState.field];
    let bValue = b[sortState.field];

    // 特殊处理月份字段的排序
    if (sortState.field === 'month') {
      // 提取年月数字进行比较
      const parseMonth = (monthStr) => {
        const match = monthStr.match(/(\d+)年(\d+)月/);
        if (match) {
          const year = parseInt(match[1]);
          const month = parseInt(match[2]);
          return year * 12 + month;
        }
        return 0;
      };
      aValue = parseMonth(aValue);
      bValue = parseMonth(bValue);
    } else {
      // 去除千位分隔符
      if (typeof aValue === 'string') {
        aValue = aValue.replace(/,/g, '');
      }
      if (typeof bValue === 'string') {
        bValue = bValue.replace(/,/g, '');
      }

      // 尝试转换为数字进行比较
      const numA = parseFloat(aValue);
      const numB = parseFloat(bValue);

      if (!isNaN(numA) && !isNaN(numB)) {
        aValue = numA;
        bValue = numB;
      }
    }

    let result = 0;
    if (aValue < bValue) {
      result = -1;
    } else if (aValue > bValue) {
      result = 1;
    }

    return sortState.order === 'asc' ? result : -result;
  });
});

// 文件输入引用
const fileInput = ref(null);

// 导出到Excel
const exportToExcel = () => {
  // 准备导出数据
  const exportData = tableData.value.map(item => {
    const exportItem = {};
    tableColumns.forEach(col => {
      exportItem[col.title] = item[col.dataIndex];
    });
    return exportItem;
  });

  // 创建工作簿
  const ws = XLSX.utils.json_to_sheet(exportData);
  const wb = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(wb, ws, '财务数据');

  // 导出文件
  XLSX.writeFile(wb, '财务数据.xlsx');
  // message.success('导出成功');
};

// 导入数据
const importFromExcel = () => {
  fileInput.value.click();
};

// 处理文件上传
const handleFileUpload = (event) => {
  const file = event.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = (e) => {
    try {
      const data = new Uint8Array(e.target.result);
      const workbook = XLSX.read(data, { type: 'array' });
      const firstSheetName = workbook.SheetNames[0];
      const worksheet = workbook.Sheets[firstSheetName];
      const jsonData = XLSX.utils.sheet_to_json(worksheet);

      if (jsonData.length === 0) {
        message.warning('Excel文件中没有数据');
        return;
      }

      // 将导入的数据转换为表格所需格式
      const importedData = jsonData.map((item, index) => {
        // 获取Excel中的数据，支持多种可能的列名
        const month = item.month || item.月份 || item['月份'] || item['month'] || '';
        const salesRevenue = parseInt(item.salesRevenue || item.销售收入 || item['销售收入'] || item['salesRevenue'] || 0);
        const materialCost = parseInt(item.materialCost || item.材料成本 || item['材料成本'] || item['materialCost'] || 0);
        const laborCost = parseInt(item.laborCost || item.人工成本 || item['人工成本'] || item['laborCost'] || 0);
        const manufacturingCost = parseInt(item.manufacturingCost || item.制造费用 || item['制造费用'] || item['manufacturingCost'] || 0);
        const otherCost = parseInt(item.otherCost || item.其他费用 || item['其他费用'] || item['otherCost'] || 0);

        // 计算总收入和总支出
        const totalIncome = salesRevenue;
        const totalExpenses = materialCost + laborCost + manufacturingCost + otherCost;
        const netProfit = totalIncome - totalExpenses;

        return {
          key: allTableData.value.length + index,
          month,
          salesRevenue: salesRevenue.toLocaleString(),
          materialCost: materialCost.toLocaleString(),
          laborCost: laborCost.toLocaleString(),
          manufacturingCost: manufacturingCost.toLocaleString(),
          otherCost: otherCost.toLocaleString(),
          totalIncome: totalIncome.toLocaleString(),
          totalExpenses: totalExpenses.toLocaleString(),
          netProfit: netProfit.toLocaleString()
        };
      });

      // 将导入的数据追加到所有数据中
      allTableData.value = [...allTableData.value, ...importedData];
      pagination.total = allTableData.value.length;

      // 更新当前页显示的数据
      updateCurrentPageData();

      console.log('导入的数据:', importedData);
      console.log('所有数据总数:', pagination.total);
      message.success(`成功导入 ${jsonData.length} 条数据，当前共 ${pagination.total} 条数据`);
    } catch (error) {
      console.error('导入失败:', error);
      message.error('导入失败: ' + error.message);
    } finally {
      // 清空文件输入
      event.target.value = '';
    }
  };
  reader.readAsArrayBuffer(file);
};
</script>

<style scoped>
.chart-page {
  padding: 10px 10px;
  background-color: #f5f5f5;
  overflow: hidden;
}

.chart-card {
  height: 100%;
}

:deep(.ant-card) {
  height: 100%;
  display: flex;
  flex-direction: column;
}

:deep(.ant-card-head) {
  flex-shrink: 0;
}

:deep(.ant-card-body) {
  flex-grow: 1;
  padding: 16px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

/* 图表标题样式容器 */
.chart-title-wrapper {
  margin: 0 -10px;
  padding: 0 10px 8px;
  position: relative;
}

.chart-title-wrapper::after {
  content: "";
  position: absolute;
  bottom: 8px;
  left: 0;
  width: 100%;
  height: 1px;
  background-color: #e8e8e8;
}

/* 图表标题文字样式 */
.chart-title-text {
  padding-bottom: 8px;
}

.custom-table-wrapper {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.table-header {
  background-color: #1F77B4 !important;
  border-bottom: 1px solid #e8e8e8;
  flex-shrink: 0;
  display: flex;
  min-width: 100%;
}

.table-header .table-cell {
  color: white;
  font-weight: bold;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 13px;
}

.table-body {
  flex-grow: 1;
  overflow-y: auto;
}

.table-row {
  display: flex;
  border-bottom: 1px solid #e8e8e8;
  min-width: 100%;
}

.table-row:last-child {
  border-bottom: none;
}

.table-head {
  font-weight: bold;
}

.table-cell {
  padding: 4px 8px;
  border-right: 1px solid #e8e8e8;
  font-size: 13px;
  white-space: nowrap;
  color: #333;
  text-align: center;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
}

.table-cell:last-child {
  border-right: none;
}

.cell-content {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}

.table-row-even {
  background-color: white;
}

.table-row-odd {
  background-color: #EFF4F9;
}

.table-body .table-row:hover {
  background-color: #e6f7ff !important;
}

.table-pagination {
  margin-top: 6px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

/* 排序相关样式 */
.sortable {
  cursor: pointer;
  user-select: none;
}
</style>
